using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CRM.Anyleads
{
    /// <summary>
    /// 邮箱有效性验证
    /// <see cref="http://emaildog.vyiqin.com/console">邮箱验证接口</see>
    /// </summary>
    public class EmailDogClient
    {
        private readonly IOptions<EmailDogConfig> _option;
        private readonly ILogger<EmailDogClient> _logger;

        public EmailDogClient(IOptions<EmailDogConfig> option, ILogger<EmailDogClient> logger)
        {
            _option = option;
            _logger = logger;
        }

        public async Task<bool> VerifyEmailState(string email)
        {
            var uri =
                $"http://api.vyiqin.com/check?key={_option.Value.Key}&email={email}";
            using var httpClient = new HttpClient();
            var res = await httpClient.GetFromJsonAsync<VerifyResponse>(uri);

            return res switch
            {
                { Status: 1 } => true,
                { Status: -1 } => false,
                _ => LogError(res),
            };

            bool LogError(VerifyResponse response)
            {
                _logger.LogInformation("{Email}: {Msg}", email, response.Msg);
                return false;
            }
        }

        private record VerifyResponse(int Status, string Msg);
    }

    public class EmailDogConfig
    {
        public string Key { get; set; }
    }
}